package com.zhiche.lisa.lspm.service.license.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.collect.Lists;
import com.zhiche.lisa.core.enums.TableStatusEnum;
import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.core.utils.Account.AccountUtil;
import com.zhiche.lisa.core.utils.Account.JwtAccountVO;
import com.zhiche.lisa.lspm.dao.model.carrier.CarrierLicense;
import com.zhiche.lisa.lspm.dao.model.driver.DriverLicense;
import com.zhiche.lisa.lspm.dao.model.lsp.LspLicense;
import com.zhiche.lisa.lspm.dao.model.trailer.TrailerLicense;
import com.zhiche.lisa.lspm.service.carrier.ICarrierLicenseService;
import com.zhiche.lisa.lspm.service.driver.IDriverLicenseService;
import com.zhiche.lisa.lspm.service.license.LicenseServier;
import com.zhiche.lisa.lspm.service.lsp.LspLicenseService;
import com.zhiche.lisa.lspm.service.trailer.TrailerLicenseService;
import com.zhiche.lisa.lspm.vo.attach.LicenseDetailVO;
import com.zhiche.lisa.lspm.vo.attach.LicenseVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class LicenseServiceImpl implements LicenseServier {
    private static final Logger LOGGER = LoggerFactory.getLogger(LicenseServiceImpl.class);
    private String DRIVER = "driver";
    private String LSP = "lsp";
    private String TRAILER = "trailer";
    private String CARRIER = "carrier";


    @Autowired
    private LspLicenseService lspLicenseService;
    @Autowired
    private ICarrierLicenseService carrierLicenseService;
    @Autowired
    private IDriverLicenseService driverLicenseService;
    @Autowired
    private TrailerLicenseService trailerLicenseService;

    /**
     * 根据所属类型和id号获取对应附件信息
     */
    @Override
    public LicenseVO queryLicenseByBelongedId(LicenseVO licenseInParam) {
        if (Objects.isNull(licenseInParam)) throw new BaseException("未获取到附件查询信息");
        try {
            //验证数据
            Long belongedId = licenseInParam.getBelongedId();
            String belongedType = licenseInParam.getBelongedType();
            if (Objects.isNull(belongedId)) throw new BaseException("未指定所属类型");
            //返回信息
            LicenseVO licenseVO = new LicenseVO();
            licenseVO.setBelongedId(belongedId);
            List<LicenseDetailVO> licenseDetailVOS = new ArrayList<>();
            //根据标识绑定结果
            if (LSP.equals(belongedType)) {
                EntityWrapper<LspLicense> ew = new EntityWrapper<>();
                ew.eq("lsp_id", belongedId);
                if (Objects.nonNull(licenseInParam.getLicenseTypeId()))
                    ew.eq("license_type_id", licenseInParam.getLicenseTypeId());
                List<LspLicense> lspLicenses = lspLicenseService.selectList(ew);
                for (LspLicense lspLicense :
                        lspLicenses) {
                    LicenseDetailVO licenseDetailVO = new LicenseDetailVO();
                    BeanUtils.copyProperties(lspLicense, licenseDetailVO);
                    licenseDetailVOS.add(licenseDetailVO);
                }
            } else if (CARRIER.equals(belongedType)) {
                EntityWrapper<CarrierLicense> ew = new EntityWrapper<>();
                ew.eq("carrier_id", belongedId);
                if (Objects.nonNull(licenseInParam.getLicenseTypeId()))
                    ew.eq("license_type_id", licenseInParam.getLicenseTypeId());
                List<CarrierLicense> carrierLicenses = carrierLicenseService.selectList(ew);
                for (CarrierLicense carrierLicense :
                        carrierLicenses) {
                    LicenseDetailVO licenseDetailVO = new LicenseDetailVO();
                    BeanUtils.copyProperties(carrierLicense, licenseDetailVO);
                    licenseDetailVOS.add(licenseDetailVO);
                }
            } else if (TRAILER.equals(belongedType)) {
                EntityWrapper<TrailerLicense> ew = new EntityWrapper<>();
                ew.eq("trailer_id", belongedId);
                if (Objects.nonNull(licenseInParam.getLicenseTypeId()))
                    ew.eq("license_type_id", licenseInParam.getLicenseTypeId());
                List<TrailerLicense> trailerLicenses = trailerLicenseService.selectList(ew);
                for (TrailerLicense trailerLicense :
                        trailerLicenses) {
                    LicenseDetailVO licenseDetailVO = new LicenseDetailVO();
                    BeanUtils.copyProperties(trailerLicense, licenseDetailVO);
                    licenseDetailVOS.add(licenseDetailVO);
                }
            } else if (DRIVER.equals(belongedType)) {
                EntityWrapper<DriverLicense> ew = new EntityWrapper<>();
                ew.eq("driver_id", belongedId);
                if (Objects.nonNull(licenseInParam.getLicenseTypeId()))
                    ew.eq("license_type_id", licenseInParam.getLicenseTypeId());
                List<DriverLicense> driverLicenses = driverLicenseService.selectList(ew);
                for (DriverLicense driverLicense :
                        driverLicenses) {
                    LicenseDetailVO licenseDetailVO = new LicenseDetailVO();
                    BeanUtils.copyProperties(driverLicense, licenseDetailVO);
                    licenseDetailVOS.add(licenseDetailVO);
                }
            } else {
                throw new BaseException("标识类型错误");
            }
            licenseVO.setLicenseDetails(licenseDetailVOS);
            return licenseVO;
        } catch (BaseException e) {
            LOGGER.error("LicenseServiceImpl.queryLspLicenseByLspId" + e.getMessage());
            throw e;
        } catch (Exception e) {
            LOGGER.error("LicenseServiceImpl.queryLspLicenseByLspId" + e.getMessage());
            throw new BaseException(e.getMessage());
        }
    }

    /**
     * 更新证照信息
     *
     * @param licenseVO
     */
    @Override
    @Transactional
    public void updateLicense(LicenseVO licenseVO) {
        try {
            if (Objects.isNull(licenseVO.getBelongedId())) throw new BaseException("未指定所属类型");
            if (Objects.nonNull(licenseVO.getLicenseDetails())) {
                if (LSP.equals(licenseVO.getBelongedType())) {
                    this.updateLspLicense(licenseVO);
                } else if (DRIVER.equals(licenseVO.getBelongedType())) {
                    this.updateDriverLicense(licenseVO);
                } else if (TRAILER.equals(licenseVO.getBelongedType())) {
                    this.updateTrailerLicense(licenseVO);
                } else if (CARRIER.equals(licenseVO.getBelongedType())) {
                    this.updateCarrierLicense(licenseVO);
                } else {
                    throw new BaseException("标识类型错误");
                }
            }
        } catch (BaseException e) {
            LOGGER.error("LicenseServiceImpl.updateLspLicense" + e.getMessage());
            throw e;
        } catch (Exception e) {
            LOGGER.error("LicenseServiceImpl.updateLspLicense" + e.getMessage());
            throw new BaseException("更新证照信息错误");
        }
    }

    /**
     * 更新挂车证照
     *
     * @param licenseVO
     */
    private void updateTrailerLicense(LicenseVO licenseVO) {
        if (!CollectionUtils.isEmpty(licenseVO.getLicenseDetails())) {
            licenseVO.getLicenseDetails().forEach(
                    licenseDetailVO -> {
                        EntityWrapper<TrailerLicense> licenseEntityWrapper = new EntityWrapper<>();
                        licenseEntityWrapper.eq("trailer_id", licenseVO.getBelongedId()).eq("license_type_id", licenseDetailVO.getLicenseTypeId());
                        List<TrailerLicense> trailerLicenses = trailerLicenseService.selectList(licenseEntityWrapper);
                        TrailerLicense trailerLicense = new TrailerLicense();
                        BeanUtils.copyProperties(licenseDetailVO, trailerLicense);
                        trailerLicense.setTrailerId(licenseVO.getBelongedId());
                        if (CollectionUtils.isEmpty(trailerLicenses)) {
                            JwtAccountVO jwtAccount = AccountUtil.getAccountInfoFromSecurityContext();
                            trailerLicense.setGmtCreate(new Date());
                            if (Objects.nonNull(jwtAccount)) {
                                trailerLicense.setCreator(jwtAccount.getAccountId());
                                trailerLicense.setTenantId(Long.parseLong(jwtAccount.getTenantId()));
                            }
                            trailerLicenseService.insert(trailerLicense);
                        } else {
                            trailerLicense.setId(trailerLicenses.get(0).getId());
                            trailerLicenseService.updateById(trailerLicense);
                        }
                    });
        }
    }

    /**
     * 更新司机证照
     */
    private void updateDriverLicense(LicenseVO licenseVO) {
        //未识别到信息
        if (CollectionUtils.isEmpty(licenseVO.getLicenseDetails()) && !StringUtils.isEmpty(licenseVO.getCardId())) {
            ArrayList<LicenseDetailVO> newLicense = Lists.newArrayList();
            LicenseDetailVO detailVO = new LicenseDetailVO();
            detailVO.setLicenseId(licenseVO.getCardId());
            detailVO.setLicenseTypeId(Long.valueOf(TableStatusEnum.STATUS_1.getCode()));
            //detailVO.setGmtReg(new Date());
            //detailVO.setGmtOverdue();
            detailVO.setGmtFirst(new Date());
            newLicense.add(detailVO);
            licenseVO.setLicenseDetails(newLicense);
        }
        //已识别到信息
        if (!CollectionUtils.isEmpty(licenseVO.getLicenseDetails())) {
            licenseVO.getLicenseDetails().forEach(
                    licenseDetailVO -> {
                        EntityWrapper<DriverLicense> licenseEntityWrapper = new EntityWrapper<>();
                        Long typeId = licenseDetailVO.getLicenseTypeId();
                        if (typeId.equals(new Long(TableStatusEnum.STATUS_1.getCode()))) {
                            //身份证
                            if (StringUtils.isEmpty(licenseDetailVO.getLicenseId())
                                    && !StringUtils.isEmpty(licenseVO.getCardId())) {
                                //新增
                                licenseDetailVO.setGmtFirst(new Date());
                                licenseDetailVO.setLicenseId(licenseVO.getCardId());
                            } else if (!StringUtils.isEmpty(licenseDetailVO.getLicenseId())
                            && !licenseDetailVO.getLicenseId().equals(licenseVO.getCardId())){
                                //修改
                                licenseDetailVO.setLicenseId(licenseVO.getCardId());
                            }
                        }
                        licenseEntityWrapper.eq("driver_id",
                                licenseVO.getBelongedId()).eq("license_type_id", typeId);
                        List<DriverLicense> driverLicenses = driverLicenseService.selectList(licenseEntityWrapper);
                        DriverLicense driverLicense = new DriverLicense();
                        BeanUtils.copyProperties(licenseDetailVO, driverLicense);
                        driverLicense.setDriverId(licenseVO.getBelongedId());
                        if (CollectionUtils.isEmpty(driverLicenses)) {
                            JwtAccountVO jwtAccount = AccountUtil.getAccountInfoFromSecurityContext();
                            driverLicense.setGmtCreate(new Date());
                            if (Objects.nonNull(jwtAccount)) {
                                driverLicense.setCreator(jwtAccount.getAccountId());
                                driverLicense.setTenantId(Long.parseLong(jwtAccount.getTenantId()));
                            }
                            driverLicenseService.insert(driverLicense);
                        } else {
                            driverLicense.setId(driverLicenses.get(0).getId());
                            driverLicenseService.updateById(driverLicense);
                        }
                    });
        }
    }

    /**
     * 更新牵引车证照
     *
     * @param licenseVO
     */
    private void updateCarrierLicense(LicenseVO licenseVO) {
        if (!CollectionUtils.isEmpty(licenseVO.getLicenseDetails())) {
            licenseVO.getLicenseDetails().forEach(
                    licenseDetailVO -> {
                        EntityWrapper<CarrierLicense> licenseEntityWrapper = new EntityWrapper<>();
                        licenseEntityWrapper.eq("carrier_id", licenseVO.getBelongedId()).eq("license_type_id", licenseDetailVO.getLicenseTypeId());
                        List<CarrierLicense> carrierLicenses = carrierLicenseService.selectList(licenseEntityWrapper);
                        CarrierLicense carrierLicense = new CarrierLicense();
                        BeanUtils.copyProperties(licenseDetailVO, carrierLicense);
                        carrierLicense.setCarrierId(licenseVO.getBelongedId());
                        if (CollectionUtils.isEmpty(carrierLicenses)) {
                            JwtAccountVO jwtAccount = AccountUtil.getAccountInfoFromSecurityContext();
                            carrierLicense.setGmtCreate(new Date());
                            if (Objects.nonNull(jwtAccount)) {
                                carrierLicense.setCreator(jwtAccount.getAccountId());
                                carrierLicense.setTenantId(Long.parseLong(jwtAccount.getTenantId()));
                            }
                            carrierLicenseService.insert(carrierLicense);
                        } else {
                            carrierLicense.setId(carrierLicenses.get(0).getId());
                            carrierLicenseService.updateById(carrierLicense);
                        }
                    });
        }
    }

    /**
     * 更新承运商证照
     *
     * @param licenseVO
     */
    private void updateLspLicense(LicenseVO licenseVO) {
        if (!CollectionUtils.isEmpty(licenseVO.getLicenseDetails())) {
            licenseVO.getLicenseDetails().forEach(
                    licenseDetailVO -> {
                        EntityWrapper<LspLicense> licenseEntityWrapper = new EntityWrapper<>();
                        licenseEntityWrapper.eq("lsp_id", licenseVO.getBelongedId()).eq("license_type_id", licenseDetailVO.getLicenseTypeId());
                        List<LspLicense> lspLicenses = lspLicenseService.selectList(licenseEntityWrapper);
                        LspLicense lspLicense = new LspLicense();
                        BeanUtils.copyProperties(licenseDetailVO, lspLicense);
                        lspLicense.setLspId(licenseVO.getBelongedId());
                        if (CollectionUtils.isEmpty(lspLicenses)) {
                            JwtAccountVO jwtAccount = AccountUtil.getAccountInfoFromSecurityContext();
                            lspLicense.setGmtCreate(new Date());
                            if (Objects.nonNull(jwtAccount)) {
                                lspLicense.setCreator(jwtAccount.getAccountId());
                                lspLicense.setTenantId(Long.parseLong(jwtAccount.getTenantId()));
                            }
                            lspLicenseService.insert(lspLicense);
                        } else {
                            lspLicense.setId(lspLicenses.get(0).getId());
                            lspLicenseService.updateById(lspLicense);
                        }
                    });
        }
    }
}
